//
//  UIColor_Extension.swift
//  zhiboxiangmu
//
//  Created by 丁丁 on 2017/7/28.
//  Copyright © 2017年 丁鼎. All rights reserved.
//

import UIKit

extension UIColor{
    
    class  func randomColor() -> UIColor {
        return UIColor(red: CGFloat(arc4random_uniform(256))/255.0, green: CGFloat(arc4random_uniform(256))/255.0, blue: CGFloat(arc4random_uniform(256))/255.0, alpha: 1)
    }
    
    

    convenience init(r: CGFloat , g :CGFloat ,b :CGFloat , a:CGFloat = 1.0) {
        self.init(red: r/255.0, green: g/255.0, blue: b/255.0, alpha: a)
    }
    
    
    convenience init?(hexString : String){
        
        //1,判断是不是6位
        guard hexString.characters.count >= 6 else {
            return nil
        }
        
        //2,转成大写
        var hexTempString = hexString.uppercased()
        
        //3,判断前2位是不是0X或者##
        if hexTempString.hasPrefix("0X") || hexTempString.hasPrefix("##")
        {
            hexTempString = (hexTempString as NSString).substring(to: 2)
            
        }
        
        //4,判断第一位是不是#
        if hexTempString.hasPrefix("#")
        {
            hexTempString = (hexTempString as NSString).substring(to: 1)
        }
        
        //5,获取RGB的三个值
        
        var range = NSRange(location: 0, length: 2)
        let rHex = (hexTempString as NSString).substring(with: range)
        range.location = 2
        let gHex = (hexTempString as NSString).substring(with: range)
        range.location = 4
        let bHex = (hexTempString as NSString).substring(with: range)
        
        
        //6,将三个16位的值转化
        
        var r:UInt32 = 0
        var g:UInt32 = 0
        var b:UInt32 = 0
        
        Scanner(string: rHex).scanHexInt32(&r)
        Scanner(string: gHex).scanHexInt32(&g)
        Scanner(string: bHex).scanHexInt32(&b)
        
        self.init(r: CGFloat(r), g: CGFloat(g), b: CGFloat(b))
    }
    

    
}


extension UIColor{
    func getRGBValue() -> (r : CGFloat , g : CGFloat,b : CGFloat){
        guard let cmp = cgColor.components else {
            fatalError("不能转化为RGB")
        }
        
        
        return(cmp[0]*255 , cmp[1]*255, cmp[2]*255)

    }
}
